package com.ganmiao.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        DecimalFormat format = new DecimalFormat("0.00#");
        if (bigDecimal != null) {
            // 保留2位小数，四舍五入
            jsonGenerator.writeString(format.format(bigDecimal));
        } else {
            jsonGenerator.writeString(format.format(BigDecimal.valueOf(0.00)));
        }
    }
}
